package com.turtle.listener;

import com.turtle.constant.SysConf;
import com.turtle.feign.EsClientService;
import com.turtle.util.SendMailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.Map;

/**
 * @author lijiayu
 * @date 2020/1/18
 * @description
 */
@Component
@Slf4j
public class SendListener {

    @Autowired
    private SendMailUtils sendMailUtils;
    @Resource
    private EsClientService blogClientService;

    @RabbitHandler
    @RabbitListener(queues = SysConf.EMAIL_DIRECT)
    public void sendEmail(Map<String,Object> map){
        String email = String.valueOf(map.get("email"));
        String type = String.valueOf(map.get(SysConf.TYPE));
        try {
            if(SysConf.CODE_EMAIL.equals(type)){
                sendMailUtils.sendCodeEmail(email);
            }else if(SysConf.FORGET_EMAIL.equals(type)){
                String userName = String.valueOf(map.get(SysConf.FORGET_EMAIL));
                sendMailUtils.sendForgetEmail(email,userName);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        log.info("email: {} send success", email);
    }

    @RabbitHandler
    @RabbitListener(queues = SysConf.BLOG_DIRECT)
    public void sendBlog(Map<String,Object> map){
        Long id = Long.valueOf(String.valueOf(map.get("id")));
        String type = String.valueOf(map.get(SysConf.TYPE));

        switch (type){
            case SysConf.ADD:
                blogClientService.addElasticIndexById(id);
                break;
            case SysConf.UPDATE:
                blogClientService.updateElasticIndexById(id);
                break;
            case SysConf.DELETE:
                blogClientService.deleteElasticIndexById(id);
                break;
            default:

        }

    }
}
